<template>
  <div class="popup_container">
    <div class="popup_header">
      <div class="popup_header_item"
           @click="toggleHeaderItem(0)"
           :class="[currentIndex == 0 ? 'active' : '']">页面二维码</div>
      <div class="popup_header_item"
           @click="toggleHeaderItem(1)"
           :class="[currentIndex == 1 ? 'active' : '']">服务连接</div>
    </div>
    <div class="popup_title">
      <p v-if="currentIndex == 0">{{windowInfo.title || windowInfo.url || '默认标题'}}</p>
      <div v-if="currentIndex == 1">
        <p>{{'扫描二维码连接页面'}}</p>
        <div class="form_item">
          <span>主机</span>
          <input ref="addressRef"
                 type="text"
                 @change="changeHost">
        </div>
        <div class="form_item">
          <span>端口号</span>
          <input ref="portRef"
                 type="text"
                 @change="changePort">
        </div>
      </div>

    </div>
    <div class="popup_qrcode"
         v-if="currentIndex == 0">
      <div class="popup_no_qrcode"
           key="noqrcode"
           v-if="!windowInfo.url">
        <div class="popup_no_qrcode_inner">请输入文字</div>
      </div>
      <div class="popup_qrcode_wrapper"
           key="qrocde"
           v-else>
        <canvas id="qrcodeWrapperRef"></canvas>
      </div>
    </div>
    <div class="popup_qrcode"
         v-if="currentIndex == 1">
      <div class="popup_qrcode_wrapper"
           key="qrocde">
        <canvas id="qrcodeWrapperRef2"></canvas>
      </div>
    </div>
    <!-- <div class="qrcode_address">
      <input v-model="windowInfo.url"
             placeholder="请输入文字"
             @keydown="input"
             @change="change"></input>
    </div> -->
    <!-- <div class="popup_bottom">
      <a type="text"
         href="javascript:void(0)"
         @click="gotoHome">更多操作</a>
    </div> -->
  </div>
</template>

<style scoped>
.popup_container {
  width: 300px;
  /*height: 400px;*/
  min-height: 400px;
  background-color: #ffffff;
}
.popup_header {
  width: 100%;
  height: 32px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.popup_header_item {
  flex: 1;
  height: 100%;
  background-color: #f5f5f5;
  color: #181818;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  transition: all 0.2s ease-in-out;
}
.popup_header_item.active {
  background-color: #4fc08d;
  /* background-color: rgb(255, 23, 42); */
  color: #ffffff;
}
.popup_title {
  width: 300px;
  font-size: 16px;
  font-weight: bold;
  padding: 15px;
  box-sizing: border-box;
  word-break: break-all;
}
.popup_title p {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
}
.popup_qrcode {
  width: 300px;
  height: 300px;
}
.popup_no_qrcode {
  width: 300px;
  height: 300px;
  padding: 15px 15px 0 15px;
  box-sizing: border-box;
  line-height: 1.5;
}
.popup_no_qrcode_inner {
  width: 100%;
  height: 100%;
  color: #dcdee2;
  font-size: 16px;
  border: 1px solid #dcdee2;
  display: flex;
  align-items: center;
  justify-content: center;
}
.qrcode_address {
  width: 300px;
  padding: 0 15px;
  box-sizing: border-box;
}
.qrcode_address input {
  width: 100%;
  margin-top: 15px;
  padding: 5px 8px;
  font-size: 14px;
  box-sizing: border-box;
}
.popup_bottom {
  width: 300px;
  padding: 15px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form_item {
  width: 100%;
  height: 32px;
  display: flex;
  flex-direction: row;
  align-items: center;
}
.form_item > span {
  font-size: 14px;
  width: 60px;
}
.form_item > input {
  flex: 1;
  height: 20px;
}
</style>

<script>
import QRCode from 'qrcode'

export default {
  name: 'Popup',
  data () {
    return {
      qrcodeHtml: '',
      windowInfo: {},
      currentIndex: 0,
      socketOptions: {},
      tmpHost: '',
      tmpPort: ''
    }
  },
  async mounted () {
    this.windowInfo = await this.getWindowInfo()

    setTimeout(() => {
      this.initQrcode()
    }, 50)
  },
  methods: {
    toggleHeaderItem (index) {
      this.currentIndex = index
      setTimeout(() => {
        this.initQrcode()
      }, 50)
    },
    getWindowInfo () {
      return new Promise(resolve => {
        // chrome.tabs.query({}, function (tabs) {
        //   console.log('>>>> Tabs:', tabs)
        // })
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
          resolve(tabs[0])
        });
      })
    },
    changeHost (e) {
      this.tmpHost = e.target.value
      setTimeout(() => {
        this.initQrcode(true)
      }, 50)
    },
    changePort (e) {
      this.tmpPort = e.target.value
      setTimeout(() => {
        this.initQrcode(true)
      }, 50)
    },
    async getSocketServerString (reconnect) {
      let bg = chrome.extension.getBackgroundPage()
      this.socketOptions = bg.socketOptions

      let addressRef = this.$refs.addressRef
      let portRef = this.$refs.portRef
      if (addressRef) {
        addressRef.setAttribute('value', this.tmpHost || this.socketOptions.host)
      }
      if (portRef) {
        portRef.setAttribute('value', this.tmpPort || this.socketOptions.port)
      }

      let _updateParams = {}
      if (this.tmpHost) {
        _updateParams['host'] = this.tmpHost
      }
      if (this.tmpPort) {
        _updateParams['port'] = this.tmpPort
      }
      return new Promise(async (resolve) => {
        await bg.resetSocketOptions(_updateParams)

        let _room = encodeURIComponent(this.windowInfo.url.split('?')[0].split('//').pop() + '|' + this.windowInfo.id + '|' + bg.fp)
        let _s = 'https://dei2.com/a/connect-socket' + encodeURIComponent(`:host=${this.tmpHost || bg.socketOptions?.host}&port=${this.tmpPort || bg.socketOptions?.port}&path=${bg.socketOptions?.path}&r=${_room}&tabId=${this.windowInfo.id}&winId=${this.windowInfo.windowId}&sid=${bg.socket.id}`)

        bg.joinRoom({
          from: this.windowInfo,
          config: {
            room: _room,
            tabId: this.windowInfo.id,
            winId: this.windowInfo.windowId
          }
        })
        resolve(this.$encrypt(_s))
      })
    },
    async initQrcode (reconnect) {
      const that = this
      if (this.currentIndex == 0) {
        if (this.windowInfo.url) {
          QRCode.toCanvas(document.getElementById('qrcodeWrapperRef'), this.windowInfo.url, {
            errorCorrectionLevel: 'H',
            width: 300,
            heihgt: 300,
            margin: 3
          }, function (err) {
            if (err) {
              throw err
            }
          })
        }
      } else if (this.currentIndex == 1) {
        let _fp = await this.getSocketServerString(reconnect)
        QRCode.toCanvas(document.getElementById('qrcodeWrapperRef2'), _fp, {
          errorCorrectionLevel: 'H',
          width: 300,
          heihgt: 300,
          margin: 3
        }, function (err) {
          if (err) {
            throw err
          }
        })
      }

    },
    input (e) {
      let keycode = e.charCode || e.keyCode
      if (keycode === 13) {
        if (window.event) {
          window.event.returnValue = false;
        } else {
          e.preventDefault(); //for firefox
        }
      }
    },
    change (e) {
      e.target.value = e.target.value.replace(/\r/ig, '').replace(/\n|\s/ig, '')
      this.windowInfo.url = e.target.value
    },
    gotoHome () {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.create({ url: chrome.extension.getURL('index.html') });
      });
    }
  },
  // watch: {
  //   'windowInfo.url' (val) {
  //     this.initQrcode()
  //   }
  // }
}
</script>
